<?php


namespace common\helpers;


use Yii;

/**
 * 统一错误处理方式
 * main.php components['errorHandler']['class'] = 'common\helpers\ErrorHandler'
 * Class ErrorHandler
 * @package common\helpers
 */
class ErrorHandler extends \yii\base\ErrorHandler
{
    protected function renderException($exception)
    {
        if (!YII_DEBUG) {
            $title = $exception->getMessage();
            $message = $exception->getFile()."：".$exception->getLine();
            $code = $exception->getCode();
            $data = commonApi::message($title,false,['title'=>$title,'message'=>$message,'code'=>$code]);
            header('Content-Type: application/json');
            echo json_encode($data);
        }else{
            echo '服务器错误';
        }
        Yii::$app->end();
    }
    public function handleFallbackExceptionMessage($exception, $previousException)
    {
        if (YII_DEBUG){
            return parent::handleFallbackExceptionMessage($exception,$previousException);
        }else{
            if (!Yii::$app->request->isAjax){
                return parent::handleFallbackExceptionMessage($exception,$previousException);
            }
        }
        return '';
    }
}